<template>
  <div class="login">
    <div class="login-title">
      <img class="login-img" src="@/assets/img/logo.png" alt="" />
    </div>
    <div class="content">
      <van-form ref="formRef" @submit="onSubmit">
        <van-cell-group inset>
          <!-- 账号密码 -->
          <template v-if="loginType">
            <van-field
              class="content-field"
              label-width="3em"
              v-model="userInfo.username"
              name="account"
              center
              label="账号"
              placeholder="请输入账号"
              :rules="FormRules.username"
              clearable
            >
              <template #left-icon>
                <svg-icon name="手机" className="form-svg"></svg-icon>
              </template>
            </van-field>
            <van-field
              class="content-field"
              label-width="3em"
              v-model="userInfo.password"
              type="password"
              name="密码"
              label="密码"
              placeholder="密码"
              center
              :rules="FormRules.password"
              clearable
            >
              <template #left-icon>
                <svg-icon name="password" className="form-svg"></svg-icon>
              </template>
            </van-field>
          </template>
          <!-- 手机号验证码 -->
          <template v-else>
            <van-field
              class="content-field"
              label-width="3em"
              v-model="accountInfo.mobile"
              name="mobile"
              center
              label="手机号"
              placeholder="请输入手机号"
              :rules="FormRules.mobile"
              clearable
            >
              <template #left-icon>
                <svg-icon name="手机" className="form-svg"></svg-icon>
              </template>
            </van-field>
            <van-field
              class="content-field"
              label-width="3em"
              v-model="accountInfo.code"
              name="code"
              label="验证码"
              placeholder="请输入验证码"
              center
              :rules="FormRules.code"
              clearable
            >
              <template #left-icon>
                <svg-icon name="password" className="form-svg"></svg-icon>
              </template>
              <template #button>
                <van-count-down
                  v-if="isCountDownShow"
                  :time="countDown * 1000"
                  format="ss s"
                  @finish="isCountDownShow = false"
                />
                <van-button
                  v-else
                  class="code-btn"
                  native-type="button"
                  size="small"
                  type="default"
                  @click="sendCodeClick"
                  >获取验证码</van-button
                >
              </template>
            </van-field>
          </template>
        </van-cell-group>
        <div class="read-agreement">
          <van-checkbox
            class="agreement-check-box"
            v-model="readAgreement"
            shape="square"
            icon-size="15px"
          />
          <div class="agreement">
            我已认真阅读且同意
            <span @click="showAgreementClick('hua')">《盛E签服务协议》</span>
            <span @click="showAgreementClick('privacy')">《隐私协议》</span>
            <span @click="showAgreementClick('number')"
              >《数字证书服务协议》</span
            >
          </div>
        </div>
        <div style="margin: 16px 29px">
          <van-button
            class="form-btn"
            block
            type="primary"
            native-type="submit"
          >
            登 录
          </van-button>
        </div>
        <div class="login-type">
          <span @click="loginType = !loginType">{{
            loginType ? '验证码登录' : '账号密码'
          }}</span>
          <div>
            <!-- 功能未开放 -->
            <!-- <span>立即注册</span>
            <span class="wire"></span>
            <span>忘记密码</span> -->
          </div>
        </div>
      </van-form>
    </div>
  </div>
  <!-- 数字协议 -->
  <DigitalCertificateProtocol ref="DigitalCertificateProtocolRef" />
  <!-- 隐私协议 -->
  <PrivacyAgreement ref="PrivacyAgreementRef" />
  <!-- 服务协议 -->
  <ServiceAgreement ref="ServiceAgreementRef" />
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from '@/store'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'vant'
import { Toast, Dialog } from 'vant'

// 方法
import {
  getSendCode,
  postAccountLogin,
  postCodeLogin,
  postUserInfo
} from '@/api/login'
// 验证规则
import { FormRules } from '@/hooks/form-config'
import DigitalCertificateProtocol from '@/components/digital-certificate-protocol'
import PrivacyAgreement from '@/components/privacy-agreement'
import ServiceAgreement from '@/components/service-agreement'
export default defineComponent({
  components: {
    DigitalCertificateProtocol,
    PrivacyAgreement,
    ServiceAgreement
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const formRef = ref<FormInstance>()
    // 登录方式
    const loginType = ref(false)
    // 账号密码
    const userInfo = reactive({
      username: '',
      password: ''
    })
    // 手机验证码
    const accountInfo = reactive({
      mobile: '',
      code: '',
      randomCode: 0
    })

    // 协议阅读
    const readAgreement = ref(false)
    const DigitalCertificateProtocolRef =
      ref<InstanceType<typeof DigitalCertificateProtocol>>()
    const PrivacyAgreementRef = ref<InstanceType<typeof PrivacyAgreement>>()
    const ServiceAgreementRef = ref<InstanceType<typeof ServiceAgreement>>()
    const showAgreementClick = (type: string) => {
      if (type === 'number') {
        DigitalCertificateProtocolRef.value!.showPopup()
      } else if (type === 'privacy') {
        PrivacyAgreementRef.value!.showPopup()
      } else if (type === 'hua') {
        ServiceAgreementRef.value!.showPopup()
      }
    }
    // 发送验证码
    const isCountDownShow = ref(false)
    const countDown = ref(0)
    const sendCodeClick = async () => {
      try {
        await formRef.value?.validate('mobile')
      } catch (error) {
        return error
      }
      try {
        accountInfo.randomCode = new Date().getTime()
        const params = {
          mobile: accountInfo.mobile,
          randomCode: accountInfo.randomCode
        }
        const res = await getSendCode(params)
        if (res.code !== '0') return
        countDown.value = Math.floor((res.data - new Date().getTime()) / 1000)
        isCountDownShow.value = true
      } catch (error) {
        return error
      }
    }

    // 登录
    const onSubmit = async () => {
      if (!readAgreement.value) {
        return Dialog.alert({
          message:
            '请勾选同意下方的盛E签服务协议，隐私协议，数字证书服务协议，方可登录'
        }).then(() => {
          // on close
        })
      }
      try {
        if (loginType.value) {
          // 密码登录
          const res = await postAccountLogin(userInfo)
          if (res.code !== '0') return
          store.commit('login/changeToken', res.data)
        } else {
          // 验证码登录
          if (!accountInfo.randomCode) {
            return Toast.fail('请先获取验证码!')
          }
          const res = await postCodeLogin(accountInfo)
          if (res.code !== '0') return
          store.commit('login/changeToken', res.data)
        }
        const resp = await postUserInfo()
        if (resp.code !== '0') return
        store.commit('login/changeUserInfo', resp.data)
        router.push('/home')
        // 获取用户信息
      } catch (error) {
        return error
      }
    }
    return {
      formRef,
      userInfo,
      FormRules,
      loginType,
      accountInfo,
      isCountDownShow,
      countDown,
      readAgreement,
      DigitalCertificateProtocolRef,
      PrivacyAgreementRef,
      ServiceAgreementRef,
      onSubmit,
      sendCodeClick,
      showAgreementClick
    }
  }
})
</script>

<style scoped lang="less">
.login {
  width: 100%;
  height: 100%;
  padding-top: 74px;
  box-sizing: border-box;
  .login-title {
    display: flex;
    justify-content: center;
    align-items: center;
    .login-img {
      width: 90px;
      height: 122px;
    }
  }
  .content {
    padding-top: 62px;
    .content-field {
      height: 64px;
      font-size: 15px;
      color: #101010;
    }
    .form-svg {
      margin-right: 8px;
    }
    .code-btn {
      color: #a5a5a5;
    }
    .form-btn {
      border-radius: 4px;
      font-size: 16px;
    }
    .read-agreement {
      display: flex;
      align-items: flex-start;
      height: 32px;
      padding: 15px 29px 0;
      .agreement-check-box {
        padding-right: 10px;
      }
      .agreement {
        font-size: 12px;
        span {
          color: #2489f2;
        }
        span:active {
          color: #8dc4fd;
        }
      }
    }
    .login-type {
      display: flex;
      justify-content: space-between;
      padding: 0 29px;
      font-size: 13px;
      color: #a5a5a5;
      .wire {
        display: inline-block;
        width: 1px;
        height: 100%;
        margin: 0 10px;
        background-color: #a5a5a5;
        vertical-align: bottom;
      }
    }
  }
}
</style>
